﻿CREATE PROCEDURE [audit].[GetTraceColumns]
@TraceName NVARCHAR (255), @Columns NVARCHAR (512) OUTPUT
AS
BEGIN
	SET @Columns = ''

	DECLARE COLUMNS_CURSOR CURSOR READ_ONLY FOR(
		SELECT [Column]
		FROM[config].[TraceDefinitions]
		WHERE([TraceName] = @TraceName)
		GROUP BY [Column]
	)
	OPEN COLUMNS_CURSOR

	DECLARE @RowIndex int
	SET @RowIndex = 0

	DECLARE @CursorRows int
	SET @CursorRows = @@CURSOR_ROWS

	DECLARE @ColName sysname	
	FETCH NEXT FROM COLUMNS_CURSOR INTO @ColName
	WHILE(@@FETCH_STATUS = 0)
		BEGIN
			SET @RowIndex = @RowIndex + 1
			SET @Columns = @Columns + CAST(@ColName AS nvarchar) +
				CASE
					WHEN (@RowIndex < @CursorRows) THEN ', '
					ELSE ''
				END
			FETCH NEXT FROM COLUMNS_CURSOR INTO @ColName
		END
	CLOSE COLUMNS_CURSOR
	DEALLOCATE COLUMNS_CURSOR
END